﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic;
using System.Text;
using System.Threading.Tasks;
using Abp;
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Configuration;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using LeadThing.AbpZeroTemplate.CameraManages.Authorization;
using LeadThing.AbpZeroTemplate.CameraManages.Dtos;
using LeadThing.AbpZeroTemplate.Dto;
using LeadThing.AbpZeroTemplate.Areas;
using LeadThing.AbpZeroTemplate.Areas.Dtos;

namespace LeadThing.AbpZeroTemplate.CameraManages
{
    /// <summary>
    /// 摄像机管理服务实现
    /// </summary>
    [AbpAuthorize(CameraManageAppPermissions.CameraManage)]


    public class CameraManageAppService : AbpZeroTemplateAppServiceBase, ICameraManageAppService
    {
        private readonly IRepository<CameraManage, long> _cameraManageRepository;
        private readonly ICameraManageListExcelExporter _cameraManageListExcelExporter;
        private readonly IRepository<Area, long> _areaRepository;
        private readonly IAreaAppService _areaAppService;
        private readonly ISqlExecuter _sqlExecuter;//sql语句接口


        private readonly CameraManageManage _cameraManageManage;
        /// <summary>
        /// 构造方法
        /// </summary>
        public CameraManageAppService(IRepository<CameraManage, long> cameraManageRepository,
        CameraManageManage cameraManageManage
      , ICameraManageListExcelExporter cameraManageListExcelExporter
      , IRepository<Area, long> areaRepository
      , IAreaAppService areaAppService
      , ISqlExecuter sqlExecuter
  )
        {
            _cameraManageRepository = cameraManageRepository;
            _cameraManageManage = cameraManageManage;
            _cameraManageListExcelExporter = cameraManageListExcelExporter;
            _areaRepository = areaRepository;
            _areaAppService = areaAppService;
            _sqlExecuter = sqlExecuter;
        }


        #region 实体的自定义扩展方法
        private IQueryable<CameraManage> _cameraManageRepositoryAsNoTrack => _cameraManageRepository.GetAll().AsNoTracking();

        private IQueryable<Area> _areaRepositoryAsNoTrack => _areaRepository.GetAll().AsNoTracking();

        /// <summary>
        /// 删除全部数据
        /// </summary>
        public int DeleteAllCameraManages()
        {
            string sql = " delete from Basic.CameraManage; ";
            return _sqlExecuter.Execute(sql);
        }

        /// <summary>
        /// 获取全部摄像机
        /// </summary>
        /// <returns></returns>
        public List<CameraManageListDto> GetAllCameraManages()
        {
            var cameraManageListDtos = _cameraManageRepository.GetAll().MapTo<List<CameraManageListDto>>();
            return cameraManageListDtos;
        }

        /// <summary>
        /// 根据摄像机ID查询是否存在匹配数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public bool IsExistenceByCameraId(GetCameraManageInput input)
        {
            bool result = false;
            var list = _cameraManageRepositoryAsNoTrack.Where(p => p.CameraId == input.Filter).ToList();
            if (list.Count() > 0)
            {
                result = true;
            }
            return result;
        }

        /// <summary>
        /// 新增摄像机管理
        /// </summary>
        public CameraManageEditDto CreateCameraManage(CameraManageEditDto input)
        {
            //TODO:新增前的逻辑判断，是否允许新增

            var entity = input.MapTo<CameraManage>();

            entity = _cameraManageRepository.Insert(entity);
            return entity.MapTo<CameraManageEditDto>();
        }

        #endregion


        #region 摄像机管理管理

        /// <summary>
        /// 根据查询条件获取摄像机管理分页列表
        /// </summary>
        public async Task<PagedResultDto<CameraManageListDto>> GetPagedCameraManagesAsync(GetCameraManageInput input)
        {

            var query = _cameraManageRepositoryAsNoTrack;
            //TODO:根据传入的参数添加过滤条件
            if (!string.IsNullOrWhiteSpace(input.Filter))
            {
                query = query.Where(p => p.CameraName.Contains(input.Filter));
            }

            //var dd = query.ToList();

            //var list = (from camera in query
            //            join area in _areaRepositoryAsNoTrack
            //            on camera.TownID equals area.Id into temp
            //            from tt in temp.DefaultIfEmpty()
            //            select new { camera, area = tt == null ? null : tt }).ToList()
            //          .Select(p => new CameraManage
            //          {
            //              Id = p.camera.Id,
            //              CameraName = p.camera.CameraName,
            //              FaultContacts = p.camera.FaultContacts,
            //              ContactNumber = p.camera.ContactNumber,
            //              Remarks = p.camera.Remarks,
            //              TownID = p.camera.TownID,
            //              AreaID = p.camera.AreaID,
            //              VillageID = p.camera.VillageID
            //          });

            //var cameraManageCount = list.Count();

            //var cameraManages = list
            //.OrderByDescending(p => p.Id)
            //.Take(input.MaxResultCount)
            //.Skip(input.SkipCount)
            //.ToList();

            //var cameraManageListDtos = cameraManages.MapTo<List<CameraManageListDto>>();
            //return new PagedResultDto<CameraManageListDto>(
            //cameraManageCount,
            //cameraManageListDtos
            //);


            var cameraManageCount = await query.CountAsync();

            var cameraManages = await query
            .OrderBy(input.Sorting)
            .PageBy(input)
            .ToListAsync();

            var cameraManageListDtos = cameraManages.MapTo<List<CameraManageListDto>>();
            return new PagedResultDto<CameraManageListDto>(
            cameraManageCount,
            cameraManageListDtos
            );
        }

        /// <summary>
        /// 通过Id获取摄像机管理信息进行编辑或修改 
        /// </summary>
        public async Task<GetCameraManageForEditOutput> GetCameraManageForEditAsync(NullableIdDto<long> input)
        {
            var output = new GetCameraManageForEditOutput();

            CameraManageEditDto cameraManageEditDto;
            output.TownList = await _areaAppService.GetAreaByLevelAsync(new GetAreaInput() { Id = 0 });

            if (input.Id.HasValue)
            {
                var entity = await _cameraManageRepository.GetAsync(input.Id.Value);
                cameraManageEditDto = entity.MapTo<CameraManageEditDto>();
                output.AreaList = await _areaAppService.GetAreaByLevelAsync(new GetAreaInput() { Id = entity.TownID });
                output.VillageList = await _areaAppService.GetAreaByLevelAsync(new GetAreaInput() { Id = entity.AreaID });
            }
            else
            {
                cameraManageEditDto = new CameraManageEditDto();
            }

            output.CameraManage = cameraManageEditDto;
            return output;
        }


        /// <summary>
        /// 通过指定id获取摄像机管理ListDto信息
        /// </summary>
        public async Task<CameraManageListDto> GetCameraManageByIdAsync(EntityDto<long> input)
        {
            var entity = await _cameraManageRepository.GetAsync(input.Id);

            return entity.MapTo<CameraManageListDto>();
        }







        /// <summary>
        /// 新增或更改摄像机管理
        /// </summary>
        public async Task CreateOrUpdateCameraManageAsync(CreateOrUpdateCameraManageInput input)
        {
            if (input.CameraManageEditDto.Id.HasValue)
            {
                await UpdateCameraManageAsync(input.CameraManageEditDto);
            }
            else
            {
                await CreateCameraManageAsync(input.CameraManageEditDto);
            }
        }

        /// <summary>
        /// 新增摄像机管理
        /// </summary>
        [AbpAuthorize(CameraManageAppPermissions.CameraManage_CreateCameraManage)]
        public virtual async Task<CameraManageEditDto> CreateCameraManageAsync(CameraManageEditDto input)
        {
            //TODO:新增前的逻辑判断，是否允许新增

            var entity = input.MapTo<CameraManage>();

            entity = await _cameraManageRepository.InsertAsync(entity);
            return entity.MapTo<CameraManageEditDto>();
        }

        /// <summary>
        /// 编辑摄像机管理
        /// </summary>
        [AbpAuthorize(CameraManageAppPermissions.CameraManage_EditCameraManage)]
        public virtual async Task UpdateCameraManageAsync(CameraManageEditDto input)
        {
            //TODO:更新前的逻辑判断，是否允许更新

            var entity = await _cameraManageRepository.GetAsync(input.Id.Value);
            input.MapTo(entity);

            await _cameraManageRepository.UpdateAsync(entity);
        }

        /// <summary>
        /// 删除摄像机管理
        /// </summary>
        [AbpAuthorize(CameraManageAppPermissions.CameraManage_DeleteCameraManage)]
        public async Task DeleteCameraManageAsync(EntityDto<long> input)
        {
            //TODO:删除前的逻辑判断，是否允许删除
            await _cameraManageRepository.DeleteAsync(input.Id);
        }

        /// <summary>
        /// 批量删除摄像机管理
        /// </summary>
        [AbpAuthorize(CameraManageAppPermissions.CameraManage_DeleteCameraManage)]
        public async Task BatchDeleteCameraManageAsync(List<long> input)
        {
            //TODO:批量删除前的逻辑判断，是否允许删除
            await _cameraManageRepository.DeleteAsync(s => input.Contains(s.Id));
        }

        #endregion

        #region 摄像机管理的Excel导出功能


        public async Task<FileDto> GetCameraManageToExcel()
        {
            var entities = await _cameraManageRepository.GetAll().ToListAsync();

            var dtos = entities.MapTo<List<CameraManageListDto>>();

            var fileDto = _cameraManageListExcelExporter.ExportCameraManageToFile(dtos);



            return fileDto;
        }


        #endregion

        #region APP
        /// <summary>
        /// 根据查询条件获取摄像机管理分页列表
        /// </summary>
        public async Task<PagedResultDto<CameraManageListAPPDto>> GetCameraManagesAppAsync(GetCameraManageAPPInput input)
        {

            var query = _cameraManageRepositoryAsNoTrack;
            //TODO:根据传入的参数添加过滤条件
            if (input.TownID > 0)
                query = query.Where(p => p.TownID == input.TownID);
            else if (input.AreaID > 0)
                query = query.Where(p => p.AreaID == input.AreaID);
            else if (input.VillageID > 0)
                query = query.Where(p => p.VillageID == input.VillageID);


            var cameraManageCount = await query.CountAsync();

            var cameraManages = await query
            .OrderBy(input.Sorting)
            .ToListAsync();

            var cameraManageListDtos = cameraManages.MapTo<List<CameraManageListAPPDto>>();
            return new PagedResultDto<CameraManageListAPPDto>(
            cameraManageCount,
            cameraManageListDtos
            );
        }
        #endregion

    }
}
